// pages/community/community.js
const { getAllArticles, updateArticlesFollowStatus, getArticlesByFollowedAuthors } = require('../../utils/articles-data');

Page({
  data: {
    currentTab: 'recommend',
    searchKeyword: '',
    recommendArticles: [],
    followArticles: [],
    currentArticles: [],
    originalRecommendArticles: [], // 保存原始推荐文章数据
    originalFollowArticles: [], // 保存原始关注文章数据
    isSearchMode: false, // 是否处于搜索模式
    hotSearchKeywords: ['英语学习', '单词记忆', '口语练习', '语法技巧', '听力训练'] // 热门搜索关键词
  },

  onLoad: function(options) {
    this.loadAllArticles();
  },

  onShow: function() {
    // 页面显示时重新加载数据
    this.loadAllArticles();
    this.loadFollowArticles();
    
    // 检查是否需要切换到关注标签
    const app = getApp();
    if (app.globalData && app.globalData.switchToFollowTab) {
      this.setData({
        currentTab: 'follow'
      });
      app.globalData.switchToFollowTab = false; // 重置标志
    }
    
    // 检查是否需要刷新数据（当文章被删除时）
    if (app.globalData && app.globalData.needRefreshCommunity) {
      this.loadAllArticles();
      app.globalData.needRefreshCommunity = false;
    }
    
    // 延迟更新文章列表，确保数据加载完成
    setTimeout(() => {
      if (this.data.currentTab === 'follow') {
        this.setData({
          currentArticles: this.data.followArticles
        });
      } else {
        this.setData({
          currentArticles: this.data.recommendArticles
        });
      }
    }, 100);
  },

  // 加载所有文章数据
  loadAllArticles: function() {
    // 从数据模块获取所有文章
    const allArticles = getAllArticles();

    // 检查关注状态
    const followedAuthors = wx.getStorageSync('followedAuthors') || [];
    const updatedArticles = updateArticlesFollowStatus(allArticles, followedAuthors);

    this.setData({
      recommendArticles: updatedArticles,
      originalRecommendArticles: updatedArticles, // 保存原始数据
      currentArticles: this.data.isSearchMode ? this.data.currentArticles : updatedArticles
    });
  },

  // 加载关注的文章
  loadFollowArticles: function() {
    const followedAuthors = wx.getStorageSync('followedAuthors') || [];
    
    // 从推荐文章中筛选出关注作者的文章
    const followArticles = this.data.recommendArticles.filter(article => 
      followedAuthors.some(author => author.id === article.author.id)
    );

    // 更新关注状态
    const updatedFollowArticles = followArticles.map(article => ({
      ...article,
      isFollowed: true
    }));

    this.setData({
      followArticles: updatedFollowArticles,
      originalFollowArticles: updatedFollowArticles // 保存原始关注文章数据
    });
  },

  // 切换推荐/关注标签
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    
    // 如果处于搜索模式，需要重新执行搜索
    if (this.data.isSearchMode && this.data.searchKeyword.trim()) {
      this.setData({
        currentTab: tab
      });
      this.performSearch(this.data.searchKeyword.trim());
    } else {
      // 正常切换标签
      this.setData({
        currentTab: tab,
        currentArticles: tab === 'recommend' ? this.data.recommendArticles : this.data.followArticles
      });
    }
  },

  // 搜索输入
  onSearchInput: function(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    
    // 实时搜索
    if (keyword.trim()) {
      this.performSearch(keyword.trim());
    } else {
      this.setData({
      currentArticles: sourceArticles,
      isSearchMode: false,
      searchKeyword: ''
    });
    }
  },

  // 搜索功能 (兼容WXML中的searchWord绑定)
  searchWord: function() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      });
      return;
    }
    
    this.performSearch(keyword);
  },

  // 执行搜索
  performSearch: function(keyword) {
    const keywordLower = keyword.toLowerCase();
    
    // 保存搜索历史
    this.saveSearchHistory(keyword);
    
    // 从原始数据中搜索
    const sourceArticles = this.data.currentTab === 'recommend' 
      ? this.data.originalRecommendArticles 
      : this.data.originalFollowArticles;
    
    const searchResults = sourceArticles.filter(article => {
      // 搜索文章标题
      const titleMatch = article.title.toLowerCase().includes(keywordLower);
      
      // 搜索作者昵称
      const authorMatch = article.author.name.toLowerCase().includes(keywordLower);
      
      // 搜索文章内容（可选）
      const contentMatch = article.content.toLowerCase().includes(keywordLower);
      
      // 搜索标签（可选）
      const tagMatch = article.tags && article.tags.some(tag => 
        tag.toLowerCase().includes(keywordLower)
      );
      
      return titleMatch || authorMatch || contentMatch || tagMatch;
    });
    
    this.setData({
      currentArticles: searchResults,
      isSearchMode: true
    });
    
    // 显示搜索结果提示
    wx.showToast({
      title: `找到 ${searchResults.length} 篇相关文章`,
      icon: searchResults.length > 0 ? 'success' : 'none',
      duration: 1500
    });
  },

  // 保存搜索历史
  saveSearchHistory: function(keyword) {
    let searchHistory = wx.getStorageSync('searchHistory') || [];
    
    // 移除重复的关键词
    searchHistory = searchHistory.filter(item => item !== keyword);
    
    // 添加到开头
    searchHistory.unshift(keyword);
    
    // 最多保存10条历史记录
    if (searchHistory.length > 10) {
      searchHistory = searchHistory.slice(0, 10);
    }
    
    wx.setStorageSync('searchHistory', searchHistory);
  },



  // 关注用户
  followUser: function(e) {
    const userId = e.currentTarget.dataset.id;
    const followedAuthors = wx.getStorageSync('followedAuthors') || [];
    
    // 查找要关注的作者信息
    const authorToFollow = this.data.recommendArticles.find(article => 
      article.author.id === userId
    )?.author;
    
    if (!authorToFollow) return;
    
    // 检查是否已经关注
    const isAlreadyFollowed = followedAuthors.some(author => author.id === userId);
    
    let updatedFollowedAuthors;
    let message;
    
    if (isAlreadyFollowed) {
      // 取消关注
      updatedFollowedAuthors = followedAuthors.filter(author => author.id !== userId);
      message = '已取消关注';
    } else {
      // 添加关注
      updatedFollowedAuthors = [...followedAuthors, authorToFollow];
      message = '关注成功';
    }
    
    // 保存到本地存储
    wx.setStorageSync('followedAuthors', updatedFollowedAuthors);
    
    wx.showToast({
      title: message,
      icon: 'success'
    });
    
    // 通知其他页面更新用户统计数据
    this.notifyProfileUpdate();
    
    // 更新推荐文章的关注状态
    const updatedRecommendArticles = this.data.recommendArticles.map(article => {
      if (article.author.id === userId) {
        return { ...article, isFollowed: !isAlreadyFollowed };
      }
      return article;
    });
    
    this.setData({
      recommendArticles: updatedRecommendArticles
    });
    
    // 重新加载关注文章列表
    this.loadFollowArticles();
    
    // 如果当前在推荐标签，更新当前显示的文章
    if (this.data.currentTab === 'recommend') {
      this.setData({
        currentArticles: updatedRecommendArticles
      });
    } else {
      // 如果在关注标签，更新为新的关注文章列表
      this.setData({
        currentArticles: this.data.followArticles
      });
    }
  },

  // 点赞文章
  likeArticle: function(e) {
    e.stopPropagation();
    const articleId = e.currentTarget.dataset.id;
    
    // 找到被点赞的文章
    const targetArticle = this.data.recommendArticles.find(article => article.id === articleId);
    if (!targetArticle) return;
    
    const newLikeStatus = !targetArticle.isLiked;
    const newLikeCount = targetArticle.isLiked ? targetArticle.likeCount - 1 : targetArticle.likeCount + 1;
    
    // 更新推荐文章列表中的点赞状态
    const updatedRecommendArticles = this.data.recommendArticles.map(article => {
      if (article.id === articleId) {
        return {
          ...article,
          isLiked: newLikeStatus,
          likeCount: newLikeCount
        };
      }
      return article;
    });
    
    // 更新关注文章列表中的点赞状态
    const updatedFollowArticles = this.data.followArticles.map(article => {
      if (article.id === articleId) {
        return {
          ...article,
          isLiked: newLikeStatus,
          likeCount: newLikeCount
        };
      }
      return article;
    });
    
    // 如果是用户发布的文章，同步更新用户发布文章列表
    this.updateUserPublishedArticleLike(articleId, newLikeCount);
    
    this.setData({
      recommendArticles: updatedRecommendArticles,
      followArticles: updatedFollowArticles,
      currentArticles: this.data.currentTab === 'recommend' ? updatedRecommendArticles : updatedFollowArticles
    });
  },

  // 更新用户发布文章的点赞数
  updateUserPublishedArticleLike: function(articleId, newLikeCount) {
    const userPublishedArticles = wx.getStorageSync('userPublishedArticles') || [];
    const updatedUserArticles = userPublishedArticles.map(article => {
      if (String(article.id) === String(articleId)) {
        return {
          ...article,
          likeCount: newLikeCount
        };
      }
      return article;
    });
    
    // 如果找到了匹配的文章，保存更新后的数据
    if (JSON.stringify(updatedUserArticles) !== JSON.stringify(userPublishedArticles)) {
      wx.setStorageSync('userPublishedArticles', updatedUserArticles);
      
      // 设置全局刷新标志
      const app = getApp();
      if (app.globalData) {
        app.globalData.needRefreshMyPublished = true;
      }
      
      // 通知my-published页面更新数据
      this.notifyMyPublishedUpdate();
    }
  },

  // 通知my-published页面更新数据
  notifyMyPublishedUpdate: function() {
    const pages = getCurrentPages();
    const myPublishedPage = pages.find(page => page.route === 'pages/my-published/my-published');
    if (myPublishedPage && myPublishedPage.loadPublishedArticles) {
      myPublishedPage.loadPublishedArticles();
    }
  },

  // 评论文章
  commentArticle: function(e) {
    e.stopPropagation();
    const articleId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${articleId}`
    });
  },

  // 分享文章
  shareArticle: function(e) {
    e.stopPropagation();
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  // 跳转到文章详情
  goToArticle: function(e) {
    const articleId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${articleId}`
    });
  },

  // 通知profile页面更新用户统计数据
  notifyProfileUpdate: function() {
    // 使用全局变量标记需要更新统计数据
    const app = getApp();
    if (app.globalData) {
      app.globalData.needUpdateStats = true;
    }
    
    // 或者直接获取当前页面栈中的profile页面并更新
    const pages = getCurrentPages();
    const profilePage = pages.find(page => page.route === 'pages/profile/profile');
    if (profilePage && profilePage.updateUserStats) {
      profilePage.updateUserStats();
    }
  }
})